/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        ListNode *resultHead = new ListNode();
        ListNode *result = resultHead;
        bool carry = false;
        while (true)
        {
            int currentSum = 0;
            if (l1 != nullptr)
            {
                currentSum += l1->val;
                l1 = l1->next;
            }
            if (l2 != nullptr)
            {
                currentSum += l2->val;
                l2 = l2->next;
            }
            if (carry)
            {
                currentSum += 1;
                carry = false;
            }
            if (!(currentSum || l1 || l2))
            {
                break;
            }
            else if (currentSum >= 10)
            {
                currentSum -= 10;
                carry = true;
            }
            result->next = new ListNode(currentSum);
            result = result->next;
        }
        if (resultHead->next == nullptr)
        {
            resultHead->next = new ListNode();
        }
        result = resultHead->next;
        delete resultHead;
        return result;
    }
};